package com.example.s11_websocket.server;


import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @auther Qiang
 * @date 2022/4/4 10:18
 */

@ServerEndpoint("/chat-room/{username}")
@Component
public class ChatServer {

    // ConcurrentHashMap 多线程时使用的Map接口实现类

    // ConcurrentHashMap 线程安全的Map
    // 定义了map保存所有连接信息
    public static final Map<String, Session> ONLINE_USER_SESSIONS = new ConcurrentHashMap<>();


    // @OnOpen 这个方法用来处理用户连上时间
    @OnOpen
    public void openSession(@PathParam("username") String username, Session session)
    {
        // 将当前连接用户加入到在线用户列表中
        ONLINE_USER_SESSIONS.put(username, session);

        String message = "欢迎用户[" + username + "] 来到聊天室！";
        System.out.println(message);
        sendMessageAll(message);
    }

    @OnMessage
    public void onMessage(@PathParam("username") String username, String message) {
        System.out.println(username+":"+message);
        sendMessageAll("用户[" + username + "] : " + message);
    }

    @OnClose
    public void onClose(@PathParam("username") String username, Session session) {
//        //当前的Session 移除
        ONLINE_USER_SESSIONS.remove(username);
//        //并且通知其他人当前用户已经离开聊天室了
        sendMessageAll("用户[" + username + "] 已经离开聊天室了！");
        System.out.println(username+"离开聊天室");
        try {
            session.close();
        } catch (IOException e) {
//            logger.error("onClose error",e);
            System.out.println(""+e.getMessage());
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
//            logger.error("onError excepiton",e);
            System.out.println(""+e.getMessage());
        }
//        logger.info("Throwable msg "+throwable.getMessage());
        System.out.println(""+throwable.getMessage());
    }


    // 给所有在线用户发送信息
    public static void sendMessageAll(String message)
    {
        // 简写方式 lamda
//        ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, message));

        for(Session s:ONLINE_USER_SESSIONS.values())
        {
            sendMessage(s,message);
        }
    }

    // 给某一个用户发送信息
    public static void sendMessage(Session session,String message)
    {
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        try {
            basic.sendText(message);
        } catch (IOException e) {
//            log.error("sendMessage IOException ",e);
            System.out.println(e.getMessage());
        }
    }

}

